import settings, os, stat
from sqlalchemy import *
from mimetypes import guess_extension
from string import atoi
from django.http import HttpResponse
from django.utils.http import http_date

def uploaded(request, file_id):
    file_id = atoi(file_id)
    meta = MetaData(bind=settings.DB_URL)    
    upload = Table('kato_upload', meta,
                   Column('kato_upload_id', Integer, Sequence('kato_upload_kato_upload_id_seq'), primary_key=True),
                   Column('kato_upload_original_name', String),
                   Column('kato_upload_mime', String))
    filedata = upload.select(upload.c.kato_upload_id == file_id).execute().fetchone()
    mimetype = filedata.kato_upload_mime
    filename = "%s/%d" % (settings.KATO_UPLOAD_DIR, file_id)
    statobj = os.stat(filename)
    contents = open(filename, 'rb').read()
    response = HttpResponse(contents, mimetype=mimetype)
    response["Last-Modified"] = http_date(statobj[stat.ST_MTIME])
    response["Content-Length"] = len(contents)
    response["Content-Disposition"] = 'attachment; filename="%s"' % filedata.kato_upload_original_name
    return response
